package com.landeb.shop.huo.frag;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SearchViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.CommentFragAdapter;
import com.landeb.shop.huo.adapter.MoneyLogActAdapter;
import com.landeb.shop.huo.bean.BeanCommentFrag;
import com.landeb.shop.huo.eventMsg.MsgResetGoodsFrag;
import com.landeb.shop.huo.httpRequest.FragCommentRequest;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CommentFragActGoodDetail extends Fragment implements View.OnClickListener {

    private static final String BASE_URL = "baseUrl";
    private String mBaseUrl;

    private String goodsId;
    private int page = 0;
    private String type = "0";
    private boolean hasNextPage = true;

    private View mView;

    private LinearLayout llAll, llGood, llMiddle, llBad;
    private RecyclerView mRecyclerView;
    private String mUrl;
    private Retrofit mRetrofit;
    private FragCommentRequest mRequest;
    private SwipeRefreshLayout mSRL;

    private CommentFragAdapter mAdapter;
    private List<BeanCommentFrag.DataBean.ListBean> mList = new ArrayList<>();

    public static CommentFragActGoodDetail newInstance(String baseUrl, String id) {
        CommentFragActGoodDetail fragment = new CommentFragActGoodDetail();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReset(MsgResetGoodsFrag event) {

        Log.e("onReset: ", "xxxxxxxxxxxxxxxxxxxxx");

        goodsId = event.getMid();
        type = "0";
        page = 1;
        hasNextPage = true;

        getComment(goodsId, page + "", type);

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);


        mBaseUrl = getArguments().getString(BASE_URL);
        goodsId = getArguments().getString("id");

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(FragCommentRequest.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_comment_frag_act_good_detail, container, false);

        initView();
        initData();

        initEvent();

        getComment(goodsId, page + "", type);

        return mView;
    }

    private void initEvent() {

        mAdapter = new CommentFragAdapter(R.layout.item_comment_frag_rv, mList,getActivity());
        mAdapter.setEnableLoadMore(true);
        mAdapter.setAutoLoadMoreSize(5);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }


        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                page=1;

                getComment(goodsId, page + "", type);
            }
        });

        mRecyclerView.addItemDecoration(
                new HorizontalDividerItemDecoration.Builder(getActivity())
                        .color(getResources().getColor(R.color.background))
                        .size(1)
                        .build());

        llAll.setOnClickListener(this);
        llGood.setOnClickListener(this);
        llMiddle.setOnClickListener(this);
        llBad.setOnClickListener(this);

    }

    private void initData() {

    }

    private void initView() {
        mSRL = (SwipeRefreshLayout) mView.findViewById(R.id.frag_comment_srl);
        llAll = (LinearLayout) mView.findViewById(R.id.frag_comment_ll_all);
        llGood = (LinearLayout) mView.findViewById(R.id.frag_comment_ll_good);
        llMiddle = (LinearLayout) mView.findViewById(R.id.frag_comment_ll_middle);
        llBad = (LinearLayout) mView.findViewById(R.id.frag_comment_ll_bad);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.frag_comment_rv);

        mSRL.setEnabled(true);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));




    }

    private void loadMore() {

        if (!hasNextPage) {
            return;
        }

        page++;

        mRequest.getComments(goodsId, page + "", type)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<BeanCommentFrag>() {
                    @Override
                    public void onCompleted() {

                        if (hasNextPage) {
                            mAdapter.loadMoreComplete();
                        } else {
                            mAdapter.loadMoreEnd();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        mAdapter.loadMoreFail();

                    }

                    @Override
                    public void onNext(BeanCommentFrag beanCommentFrag) {

                        if (beanCommentFrag.getStatus() == 1) {

                            mList.addAll(beanCommentFrag.getData().getList());
                            mAdapter.notifyDataSetChanged();

                            hasNextPage = (beanCommentFrag.getData().getMore() == 1) ? true : false;


                        } else {
                            Toast.makeText(getActivity(), beanCommentFrag.getInfo(), Toast.LENGTH_SHORT).show();
                        }


                    }
                });


    }

    private void getComment(String goodsId, String page, String type) {

        mSRL.setRefreshing(true);

        mRequest.getComments(goodsId, page, type)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<BeanCommentFrag>() {
                    @Override
                    public void onCompleted() {
                        mSRL.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mSRL.setRefreshing(false);

                    }

                    @Override
                    public void onNext(BeanCommentFrag beanCommentFrag) {

                        if (beanCommentFrag.getStatus() == 1) {

                            mList.clear();
                            mList.addAll(beanCommentFrag.getData().getList());
                            mAdapter.notifyDataSetChanged();

                            hasNextPage = (beanCommentFrag.getData().getMore() == 1) ? true : false;


                        } else {
                            Toast.makeText(getActivity(), beanCommentFrag.getInfo(), Toast.LENGTH_SHORT).show();
                        }


                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.frag_comment_ll_all:

                type = "0";
                page = 1;
                hasNextPage = true;
                getComment(goodsId, page + "", type);

                break;

            case R.id.frag_comment_ll_good:

                type = "1";
                page = 1;
                hasNextPage = true;

                getComment(goodsId, page + "", type);

                break;

            case R.id.frag_comment_ll_middle:

                type = "2";
                page = 1;

                hasNextPage = true;
                getComment(goodsId, page + "", type);

                break;

            case R.id.frag_comment_ll_bad:

                type = "3";
                page = 1;
                hasNextPage = true;

                getComment(goodsId, page + "", type);

                break;


        }


    }
}
